from flask import Blueprint, render_template, request, redirect, url_for
from models import house
import math
list_page = Blueprint('list_page', __name__)


@list_page.route('/list/pattern/<int:page>')
def return_new_list(page):

    house_num = house.query.count()

    total_num = math.ceil(house_num / 10)
    result = house.query.order_by(house.publish_time.desc()).paginate(page=page, per_page=10)
    print("房源总数为：", house_num)
    print("房源总页码数为：", total_num)
    print("当前房源信息为：", result)
    return render_template('list.html',
                           house_list=result.items,
                           page_num=result.page, total_num=total_num)


@list_page.route('/query')
def search_txt_info():

    house_num = house.query.count()
    total_num = math.ceil(house_num / 10)

    if request.args.get('addr'):
        addr = request.args.get('addr')
        result = house.query.filter(house.address == addr).order_by(house.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)

    if request.args.get('rooms'):
        rooms_info = request.args.get('rooms')
        result = house.query.filter(house.rooms == rooms_info).order_by(house.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)
    return redirect(url_for('index_page.index'))


@list_page.route('/list/hot_house/<int:page>')
def return_hot_list(page):

    house_num = house.query.count()

    total_num = math.ceil(house_num / 10)
    result = house.query.order_by(
        house.page_views.desc()).paginate(page=page, per_page=10)
    print(result.items)
    return render_template('list.html', house_list=result.items, page_num=result.page, total_num=total_num)


def deal_title_over(word):
    if len(word) > 15:
        return word[:15] + '...'
    else:
        return word


def deal_direction(word):
    if len(word) == 0 or word is None:
        return '暂无信息'
    else:
        return word


list_page.add_app_template_filter(deal_title_over, 'dealover')
list_page.add_app_template_filter(deal_direction, 'dealdirection')